﻿using AutoUpdateTool.Models;
using AutoUpdateTool.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace AutoUpdateTool
{
    /// <summary>
    /// 自动更新清单文件配置程序
    /// </summary>
    public partial class MainForm : Form
    {
        private ToolTip tooltip;
        private MainForm _currentFrm;
        private SettingForm _settForm;
        private System.Windows.Forms.DataGridView _dataGridView;

        private UptBaseModel _modelBase = new UptBaseModel(); //自动更新清单文件缓存对象
        private string _selfHostUrl = "http://localhost:31113/api/file/";

        public MainForm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            _dataGridView = CreatePanelView(this.panel_view);
            _currentFrm = this;

            _currentFrm.tooltip = new ToolTip();
            _currentFrm.tooltip.InitialDelay = 200;
            _currentFrm.tooltip.ReshowDelay = 200;
            _currentFrm.tooltip.ShowAlways = true;
            _currentFrm.tooltip.IsBalloon = true;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                _currentFrm.lbl_checkconfig.Visible = false;
                if (!Common.InitLocked || string.IsNullOrWhiteSpace(Common.AppRootPath))
                    _currentFrm.lbl_checkconfig.Visible = true;

                _currentFrm.tooltip.SetToolTip(this.btnServer, "使用内置文件服务，请务必将服务地址设置为如下格式 \r\n http://localhost:<port>/api/file/");

                //配置文件路径
                SetConfigPathText(Common.TrailingFilePath(Common.FilesRootPath + Common.ManifestName));

                _currentFrm._modelBase = Common.ReadAutoUpdateMapsXml(_currentFrm.link_confpath.Text);//读取清单置文件
                _currentFrm._modelBase.server = string.IsNullOrWhiteSpace(_currentFrm._modelBase.server) ? _selfHostUrl : _currentFrm._modelBase.server;
                ReloadMainContents(_currentFrm._modelBase);//加载到界面
                ReloadDgvDataSource(_currentFrm._modelBase);
                _currentFrm.panel_checknew.Visible = Common.CheckChangeFiles(_currentFrm._modelBase);//检测清单内文件是否改动
            }
            catch (Exception ex)
            {
                MsgView.ShowText(ex.Message + "\r\n" + ex.InnerException);
            }
        }

        #region 按钮 读取更新清单文件
        /// <summary>
        /// 读取配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRead_Click(object sender, EventArgs e)
        {
            try
            {
                var selectxml = string.Empty;
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = false;//该值确定是否可以选择多个文件
                dialog.Title = "请选择文件";
                dialog.FileName = Common.ManifestName;
                dialog.Filter = "XML文件(*.xml)|*.xml";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Console.WriteLine(dialog.FileName);
                    selectxml = dialog.FileName;
                }

                if (!string.IsNullOrWhiteSpace(selectxml))
                {
                    _currentFrm.Invoke(new MAction(() => {

                        SetConfigPathText(selectxml);

                        //设置更新文件目录为配置文件目录
                        Common.FilesRootPath = Path.GetDirectoryName(dialog.FileName) + "\\";
                        _currentFrm._modelBase = Common.ReadAutoUpdateMapsXml(_currentFrm.link_confpath.Text);//读取清单置文件
                        ReloadMainContents(_currentFrm._modelBase);//加载到界面
                        ReloadDgvDataSource(_currentFrm._modelBase);
                        _currentFrm.panel_checknew.Visible = Common.CheckChangeFiles(_currentFrm._modelBase);//检测清单内文件是否改动
                    }));
                }
            }
            catch (Exception ex)
            {
                MsgView.ShowText("清单文件读取失败：\r\n" + ex.Message);
            }
        }
        #endregion

        #region 按钮 保存更新清单文件
        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnApply_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(_currentFrm.txtUrlRoot.Text))
                {
                    MessageBox.Show("请输入文件服务地址", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                _currentFrm._modelBase.server = new Uri(_currentFrm.txtUrlRoot.Text).ToString();

                if (string.IsNullOrEmpty(_currentFrm.txtVersion.Text))
                {
                    MessageBox.Show("请输入主程序版本号", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                _currentFrm._modelBase.version = _currentFrm.txtVersion.Text;

                Common.SaveAutoUpdateMapsXml(_currentFrm._modelBase, _currentFrm.link_confpath.Text);

                _currentFrm.panel_checknew.Visible = Common.CheckChangeFiles(_currentFrm._modelBase);//检测清单内文件是否改动

                MessageBox.Show("保存成功!");
            }
            catch (Exception ex)
            {
                MsgView.ShowText("保存配置文件失败：\r\n" + ex.Message);
            }
        }

        private void SetConfigPathText(string path)
        {
            _currentFrm.link_confpath.Text = path;
            _currentFrm.tooltip.SetToolTip(_currentFrm.link_confpath, _currentFrm.link_confpath.Text + (File.Exists(path) ? "" : "(未保存)"));
        }

        #endregion

        #region 按钮 内置HTTP服务设置
        private void btnServer_Click(object sender, EventArgs e)
        {
            try
            {
                if (SelfHostUtils.IsRunning == false)
                {
                    //启动自宿主文件服务
                    var flag = SelfHostUtils.StartServer(_currentFrm.txtUrlRoot.Text);
                    if (flag)
                    {
                        _currentFrm.btnServer.Text = "停止服务";
                        MsgView.ShowToast($"内置HTTP服务已启动！\r\n\r\n服务地址：{_currentFrm.txtUrlRoot.Text}\r\n\r\n服务路径：{AppDomain.CurrentDomain.BaseDirectory}");
                    }
                }
                else
                {
                    //启动自宿主文件服务
                    var flag = SelfHostUtils.StopServer();
                    if (flag) _currentFrm.btnServer.Text = "启动服务";
                }
            }
            catch (AggregateException ex)
            {
                string text = "内置HTTP服务启动失败！\r\n\r\n请尝试使用管理员权限运行程序再启动内置服务\r\n或者运行以下命令行后再次尝试：\r\n netsh http add urlacl url=http://+:31113/ user=Everyone \r\n\r\n异常原因：\r\n" + ex.InnerException?.Message + ex.InnerException.StackTrace;
                MsgView.ShowText(text);
                //throw ex.InnerException;
            }
        }
        #endregion

        #region 菜单 添加文件到列表
        /// <summary>
        /// 添加文件到列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuAdd_Click(object sender, EventArgs e)
        {
            try
            {
                _currentFrm._modelBase.server = _currentFrm.txtUrlRoot.Text;

                if (string.IsNullOrEmpty(_currentFrm.txtUrlRoot.Text))
                {
                    MessageBox.Show("请输入更新服务地址", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    _currentFrm.txtUrlRoot.Focus();
                    return;
                }
                _currentFrm.Invoke(new MAction(() => {
                    SelectFilesDatas(_currentFrm._modelBase);
                    //配置文件路径
                    SetConfigPathText(Common.TrailingFilePath(Common.FilesRootPath + Common.ManifestName));
                }));

                ReloadDgvDataSource(_currentFrm._modelBase);
            }
            catch (Exception ex)
            {
                MsgView.ShowText(ex.Message);
            }
        }
        #endregion

        #region 菜单 移除勾选的行
        /// <summary>
        /// 移除勾选文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (_dataGridView == null) return;
                foreach (DataGridViewRow row in _dataGridView.Rows)
                {
                    var hash1 = row.Cells["col_Hash1"].Value.ToString();
                    var isChecked = Convert.ToBoolean(row.Cells["col_Sel"].EditedFormattedValue);
                    if (isChecked)
                    {
                        Common.RemoveFileModel(_currentFrm._modelBase, hash1);
                    }
                }
                //刷新显示
                ReloadDgvDataSource(_currentFrm._modelBase);
            }
            catch (Exception ex)
            {
                MsgView.ShowText(ex.Message);
            }
        }

        #endregion

        #region 菜单 清空文件列表
        /// <summary>
        /// 清空文件列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuCls_Click(object sender, EventArgs e)
        {
            try
            {
                _currentFrm._modelBase.files.Clear();

                ReloadDgvDataSource(_currentFrm._modelBase);
            }
            catch (Exception ex)
            {
                MsgView.ShowText(ex.Message);
            }
        }
        #endregion

        #region LINK 打开清单文件所在目录
        /// <summary>
        /// 打开清单文件所在目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void link_confpath_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (File.Exists(_currentFrm.link_confpath.Text))
            {
                System.Diagnostics.Process.Start("explorer.exe", string.Format(@"/select,{0}", _currentFrm.link_confpath.Text));
            }
            else
            {
                System.Diagnostics.Process.Start("explorer.exe", Path.GetDirectoryName(_currentFrm.link_confpath.Text));
            }
        }
        #endregion

        #region LINK 更新并保存清单文件
        private void link_flashconfig_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            _currentFrm.panel_checknew.Visible = false;

            _currentFrm._modelBase = Common.ReadAutoUpdateMapsXml(_currentFrm.link_confpath.Text);//读取清单置文件
            ReloadMainContents(_currentFrm._modelBase);//加载到界面
            ReloadDgvDataSource(_currentFrm._modelBase);
            
            //更新并保存清单文件
            if (_currentFrm._modelBase.files != null && _currentFrm._modelBase.files.Count > 0)
            {

                Common.ReloadAutoUpdateMaps(_currentFrm._modelBase, Common.FilesRootPath);
                Common.SaveAutoUpdateMapsXml(_currentFrm._modelBase, _currentFrm.link_confpath.Text);
            }
        }
        private void txtUrlRoot_TextChanged(object sender, EventArgs e)
        {
            if (Common.IsIPAddress(_currentFrm.txtUrlRoot.Text))
            {
                _currentFrm._modelBase.server = new Uri(_currentFrm.txtUrlRoot.Text).ToString();

                Common.ReloadAutoUpdateMaps(_currentFrm._modelBase, Common.FilesRootPath);
                ReloadDgvDataSource(_currentFrm._modelBase);
            }
        }
        #endregion

        #region LINK 生成自动更新加密ini配置
        private void lbl_makeini_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ShowSettingForm();
        }
        #endregion

        #region 私有方法
        private void ReloadMainContents(UptBaseModel modelData)
        {
            _currentFrm.Invoke(new MAction(() =>
            {
                _currentFrm.txtVersion.Text = modelData.version;
                _currentFrm.txtDescription.Text = modelData.description;
                _currentFrm.txtUrlRoot.Text = string.IsNullOrEmpty(_currentFrm._modelBase.server) ? _currentFrm.txtUrlRoot.Text : modelData.server;
                _currentFrm.txtUrlRoot.Focus();
            }));
        }

        /// <summary>
        /// 数据重新加载到DataGridView
        /// </summary>
        /// <param name="panel"></param>
        /// <param name="modelBase"></param>
        private void ReloadDgvDataSource(UptBaseModel modelBase)
        {
            _currentFrm.Invoke(new MAction(() => {
                if (_dataGridView == null) _dataGridView = CreatePanelView(_currentFrm.panel_view);
                List<FileInfoModel_View> temp = new List<FileInfoModel_View>();
                foreach (var item in modelBase.files)
                {
                    FileInfoModel_View info = new FileInfoModel_View();
                    info.hash1 = item.hash1;
                    info.fileName = item.fileName;
                    info.filePath = item.filePath;
                    info.fileVer = item.fileVer;
                    info.fileBytes = FileOperate.GetSizeString(item.fileBytes);
                    info.fileDrect = item.fileDrect;
                    info.urlDrect = item.urlDrect;
                    info.lastWTime = item.lastWTime;
                    temp.Add(info);
                }
                _dataGridView.DataSource = temp;
                if (_dataGridView.Rows.Count > 0)
                {
                    _dataGridView.Rows[0].Selected = false;
                }
            }));
        }

        /// <summary>
        /// 选择文件，添加文件信息到清单缓存列表 List<FileInfoModel>
        /// </summary>
        /// <param name="modelData"></param>
        private void SelectFilesDatas(UptBaseModel modelData)
        {
            // 选择文件夹
            string[] files = Common.SelectFolderOrFiles();
            if (files != null && files.Length > 0)
            {
                var rootPath = Common.GetCommonParentDirectory(files, Common.FilesRootPath);
                modelData.server = new Uri(_currentFrm.txtUrlRoot.Text).ToString();
                
                foreach (string filePath in files)
                {
                    Common.ReflashOrAddFileModel(modelData, filePath, rootPath);
                }
            }
        }
        /// <summary>
        /// 显示配置窗体
        /// </summary>
        private void ShowSettingForm()
        {
            if (_settForm == null || _settForm.IsDisposed)
            {
                _settForm = new SettingForm();
                _settForm.Owner = this;
                _settForm.ShowDialog();
            }
            else if (_settForm.Visible == false)
            {
                _settForm.Owner = this;
                _settForm.ShowDialog();
            }
        }
        #endregion

        #region 初始化 DataGridView
        private DataGridView CreatePanelView(Panel panel)
        {
            System.Windows.Forms.DataGridView dgv = new System.Windows.Forms.DataGridView();

            #region 右键菜单
            System.Windows.Forms.ContextMenuStrip menuStrip = new System.Windows.Forms.ContextMenuStrip();
            menuStrip.Name = "menuStrip";
            menuStrip.Size = new System.Drawing.Size(153, 48);

            System.Windows.Forms.ToolStripMenuItem menuAdd = new System.Windows.Forms.ToolStripMenuItem();
            menuAdd.Text = "添加文件";
            menuAdd.Click += new EventHandler(menuAdd_Click);

            System.Windows.Forms.ToolStripMenuItem menuDel = new System.Windows.Forms.ToolStripMenuItem();
            menuDel.Text = "移除勾选";
            menuDel.Click += new EventHandler(menuDel_Click);

            System.Windows.Forms.ToolStripMenuItem menuCls = new System.Windows.Forms.ToolStripMenuItem();
            menuCls.Text = "清空列表";
            menuCls.Click += new EventHandler(menuCls_Click);

            menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                menuAdd, menuDel, menuCls
            });
            #endregion

            #region DataGridView数据列

            // 勾选框
            System.Windows.Forms.DataGridViewCheckBoxColumn col_Sel = new System.Windows.Forms.DataGridViewCheckBoxColumn();
            col_Sel.FalseValue = "";
            col_Sel.HeaderText = "勾选";
            col_Sel.Name = "col_Sel";
            col_Sel.TrueValue = "";
            col_Sel.Width = 40;
            col_Sel.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            col_Sel.Resizable = DataGridViewTriState.False;

            // 移除
            System.Windows.Forms.DataGridViewLinkColumn col_Del = new System.Windows.Forms.DataGridViewLinkColumn();
            col_Del.HeaderText = "操作";
            col_Del.Name = "col_Del";
            col_Del.Text = "移除";
            col_Del.Width = 40;
            col_Del.LinkBehavior = System.Windows.Forms.LinkBehavior.NeverUnderline;
            col_Del.UseColumnTextForLinkValue = true;
            col_Del.VisitedLinkColor = System.Drawing.Color.Blue;
            col_Del.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            col_Del.Resizable = DataGridViewTriState.False;

            // 文件名
            System.Windows.Forms.DataGridViewTextBoxColumn col_FileName = new System.Windows.Forms.DataGridViewTextBoxColumn();
            col_FileName.DataPropertyName = "fileName";
            col_FileName.HeaderText = "文件名";
            col_FileName.Name = "col_FileName";
            col_FileName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            col_FileName.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            col_FileName.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            col_FileName.Resizable = DataGridViewTriState.True;

            // 文件路径
            System.Windows.Forms.DataGridViewTextBoxColumn col_FilePath = new System.Windows.Forms.DataGridViewTextBoxColumn();
            col_FilePath.DataPropertyName = "filePath";
            col_FilePath.HeaderText = "文件路径";
            col_FilePath.Name = "col_FilePath";
            col_FilePath.Width = 150;
            col_FilePath.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            col_FilePath.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            col_FilePath.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            col_FilePath.Resizable = DataGridViewTriState.True;

            // 版本号
            System.Windows.Forms.DataGridViewTextBoxColumn col_FileVersion = new System.Windows.Forms.DataGridViewTextBoxColumn();
            col_FileVersion.DataPropertyName = "fileVer";
            col_FileVersion.HeaderText = "版本号";
            col_FileVersion.Name = "col_FileVersion";
            col_FileVersion.Width = 80;
            col_FileVersion.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            col_FileVersion.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            col_FileVersion.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            col_FileVersion.Resizable = DataGridViewTriState.True;

            // 创建时间
            System.Windows.Forms.DataGridViewTextBoxColumn col_LastWTime = new System.Windows.Forms.DataGridViewTextBoxColumn();
            col_LastWTime.DataPropertyName = "lastWTime";
            col_LastWTime.HeaderText = "创建时间";
            col_LastWTime.MinimumWidth = 20;
            col_LastWTime.Name = "col_LastWTime";
            col_LastWTime.Width = 120;
            col_LastWTime.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            col_LastWTime.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            col_LastWTime.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            col_LastWTime.Resizable = DataGridViewTriState.True;

            // 链接地址
            System.Windows.Forms.DataGridViewTextBoxColumn col_UrlDrect = new System.Windows.Forms.DataGridViewTextBoxColumn();
            col_UrlDrect.DataPropertyName = "urlDrect";
            col_UrlDrect.HeaderText = "链接地址";
            col_UrlDrect.Name = "col_UrlDrect";
            col_UrlDrect.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            col_UrlDrect.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            col_UrlDrect.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            col_UrlDrect.Resizable = DataGridViewTriState.True;

            // 文件大小
            System.Windows.Forms.DataGridViewTextBoxColumn col_FileBytes = new System.Windows.Forms.DataGridViewTextBoxColumn();
            col_FileBytes.DataPropertyName = "fileBytes";
            col_FileBytes.HeaderText = "文件大小";
            col_FileBytes.Name = "col_FileBytes";
            col_FileBytes.Width = 70;
            col_FileBytes.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            col_FileBytes.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            col_FileBytes.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            col_FileBytes.Resizable = DataGridViewTriState.True;

            // 文件HASH1
            System.Windows.Forms.DataGridViewTextBoxColumn col_Hash1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            col_Hash1.DataPropertyName = "hash1";
            col_Hash1.HeaderText = "文件指纹";
            col_Hash1.Name = "col_Hash1";
            col_Hash1.Visible = false;

            // 目标路径
            System.Windows.Forms.DataGridViewTextBoxColumn col_FileDrect = new System.Windows.Forms.DataGridViewTextBoxColumn();
            col_FileDrect.DataPropertyName = "fileDrect";
            col_FileDrect.HeaderText = "目标路径";
            col_FileDrect.Name = "col_FileDrect";
            col_FileDrect.Visible = false;
            col_FileDrect.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;

            System.Windows.Forms.DataGridViewColumn[] columns = new System.Windows.Forms.DataGridViewColumn[] {
                col_Sel, col_Del, col_FileName, col_FilePath, col_FileVersion, col_LastWTime, col_UrlDrect, col_FileBytes, col_Hash1, col_FileDrect
            };
            #endregion

            #region DataGridView设置
            dgv.Name = "AutoUpdateMapsDgv";
            dgv.Dock = DockStyle.Fill;
            dgv.ScrollBars = ScrollBars.Both;
            dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgv.MultiSelect = true;
            dgv.BackgroundColor = System.Drawing.Color.Snow;
            dgv.BorderStyle = BorderStyle.None;
            dgv.GridColor = System.Drawing.Color.LightGray;
            dgv.RowHeadersVisible = false;//左侧空白列隐藏
            dgv.AllowUserToResizeColumns = false;//不允许调整列
            dgv.AllowUserToResizeRows = false;//不允许调整行
            dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;//禁止拖动标题行高度
            dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//标题行内容在垂直水平方向均居中
            dgv.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//单元格内容在垂直水平方向均居中
            dgv.ColumnHeadersHeight = 30;//设置列标题行高为30
            dgv.RowTemplate.Height = 23;//设置单元格行高为23
            dgv.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("微软雅黑", 9, System.Drawing.FontStyle.Bold);
            dgv.RowsDefaultCellStyle.Font = new System.Drawing.Font("微软雅黑", 8.2F, System.Drawing.FontStyle.Regular);
            dgv.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            dgv.AllowUserToAddRows = false;//不显示添加行

            //设置右键菜单
            dgv.ContextMenuStrip = menuStrip;
            //添加数据列
            dgv.Columns.AddRange(columns);
            //行点击事件
            dgv.CellClick += dgv_CellClick;
            #endregion

            panel.Controls.Add(dgv);
            return dgv;
        }

        /// <summary>
        /// 行点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                var dgv = ((DataGridView)sender);
                if (dgv == null) return;

                var clickedCell = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex];
                if (clickedCell == null) return;
                var columnsName = dgv.Columns[clickedCell.ColumnIndex]?.Name;
                if (string.IsNullOrWhiteSpace(columnsName)) return;

                if (columnsName == "col_Del" && clickedCell.Value?.ToString() == "移除")
                {
                    var hash1 = dgv.Rows[e.RowIndex].Cells["col_Hash1"].Value.ToString();

                    Common.RemoveFileModel(_currentFrm._modelBase, hash1);

                    //刷新显示
                    ReloadDgvDataSource(_currentFrm._modelBase);
                }
            }
        }
        #endregion

        #region 窗体无边框可拖动
        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wparam, int lparam);
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            if (e.Button == MouseButtons.Left)//鼠标左键            
            {
                Capture = false;//释放鼠标
                SendMessage(Handle, 0x00A1, 2, 0);//拖动窗体            
            }
        }

        [DllImport("User32.DLL")]
        public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
        [DllImport("User32.DLL")]
        public static extern bool ReleaseCapture();
        public const uint WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 61456;
        public const int HTCAPTION = 2;

        private void Control_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
        }
        #endregion

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.GC.Collect();
            if (e.CloseReason == CloseReason.UserClosing)
            {
                // 阻止默认的关闭行为
                e.Cancel = true;

                // 强制关闭应用程序
                Environment.Exit(0);
            }
        }
    }
}
